package com.huilian.test.pdf;

import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


/**
 * 
 * @Title: PdfUtil.java
 * @Package com.huilian.hlej.contract.util
 * @Description: PDF转图片
 * @author Liqi
 * @date 2017年8月4日 上午11:07:34
 */
public class PdfToPicUtil {
	private static Logger logger = LoggerFactory.getLogger(PdfToPicUtil.class);
	/**
	 * 将PDF转换图片
	 * 
	 * @param sourceData
	 * @return
	 */
	public static byte[] toImg(byte[] sourceData,String format) {
		byte[] rsData = null;
		PDDocument doc = null;
		PDFRenderer renderer = null;
		try {
			doc = PDDocument.load(sourceData);
			renderer = new PDFRenderer(doc);
			List<BufferedImage> piclist = new ArrayList<BufferedImage>();
			int pageCount = doc.getNumberOfPages();
			for (int i = 0; i < pageCount; i++) {
				BufferedImage image = renderer.renderImageWithDPI(i, 296);
				// 压缩图片
				image = disposeImage(image,image.getWidth()/2,image.getHeight()/2);
				piclist.add(image);
			}
			rsData = yPic(piclist,format);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(doc != null) doc.close();
			} catch (IOException e) {
			}
		}
		return rsData;

	}
	public static byte[] toImg(byte[] sourceData) {
		return toImg(sourceData, "jpg");
	}

	/**
	 * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同
	 * 
	 * @param piclist
	 *            文件流数组
	 * @param outPath
	 *            输出路径
	 */
	public static byte[] yPic(List<BufferedImage> piclist,String format) {// 纵向处理图片
		byte[] bytes = null;
		if (piclist == null || piclist.size() <= 0) {
			return bytes;
		}
		try {
			int height = 0, // 总高度
					width = 0, // 总宽度
					_height = 0, // 临时的高度 , 或保存偏移高度
					__height = 0, // 临时的高度，主要保存每个高度
					picNum = piclist.size();// 图片的数量
			int[] heightArray = new int[picNum]; // 保存每个文件的高度
			BufferedImage buffer = null; // 保存图片流
			List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
			int[] _imgRGB; // 保存一张图片中的RGB数据
			for (int i = 0; i < picNum; i++) {
				buffer = piclist.get(i);
				heightArray[i] = _height = buffer.getHeight();// 图片高度
				if (i == 0) {
					width = buffer.getWidth();// 图片宽度
				}
				height += _height; // 获取总高度
				_imgRGB = new int[width * _height];// 从图片中读取RGB
				_imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
				imgRGB.add(_imgRGB);
			}
			_height = 0; // 设置偏移高度为0
			logger.info("-------------1----width:"+width+";height:"+height);
			// 生成新图片
			BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			logger.info("-------------imageResult----");
			for (int i = 0; i < picNum; i++) {
				__height = heightArray[i];
				if (i != 0)
					_height += __height; // 计算偏移高度
				imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(imageResult, "jpg", baos);
			bytes = baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bytes;
	}
	
	/**  
     * 处理图片 
     * @param src  
     * @param new_w  
     * @param new_h  
     */  
    private synchronized static BufferedImage disposeImage(BufferedImage src,int new_w,int new_h) {  
        // 得到图片  
        int old_w = src.getWidth();  
        // 得到源图宽  
        int old_h = src.getHeight();  
        // 得到源图长  
        BufferedImage newImg = null;  
        // 判断输入图片的类型  
        switch (src.getType()) {  
        case 13:  
            // png,gifnewImg = new BufferedImage(new_w, new_h,  
            // BufferedImage.TYPE_4BYTE_ABGR);  
            break;  
        default:  
            newImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);  
            break;  
        }  
        Graphics2D g = newImg.createGraphics();  
        // 从原图上取颜色绘制新图  
        g.drawImage(src, 0, 0, old_w, old_h, null);  
        g.dispose();  
        // 根据图片尺寸压缩比得到新图的尺寸  
        newImg.getGraphics().drawImage(  
                src.getScaledInstance(new_w, new_h, Image.SCALE_SMOOTH), 0, 0,  
                null);  
       return newImg;
    }

	public static void main(String[] args) throws IOException {
		String filePath="C:\\Users\\luod\\Downloads\\SCC20181011150602339708369.pdf";
		byte[] imgData = PdfToPicUtil.toImg(IOUtils.toByteArray(new FileInputStream(filePath)));
		IOUtils.write(imgData,new FileOutputStream("C:\\Users\\luod\\Downloads\\SCC20180827103731985777580.jpg"));
		IOUtils.closeQuietly();
	}
}
